<template>
  <el-button type="success" @click="dialogVisible = true">添加订单</el-button>
  <el-dialog v-model="dialogVisible">
    <el-form :model="formModel" ref="form" :rules="formRules" label-width="100px">
      <el-form-item label="酒店名" prop="hname">
        <el-select :data="hoteldata" placeholder="选择酒店" v-model="formModel.hname" size="large" @change="selectHotelroom">
          <el-option v-for="(hotels, index) in hoteldata" :key="index" :label="hotels.name" :value="hotels.hid" />
        </el-select>
      </el-form-item>
      <el-form-item label="房间号" prop="rid">
        <el-select :data="options" placeholder="选择房间" v-model="formModel.rid" size="large">
          <el-option v-for="(room, index) in options" :key="index" :label="room.rid" :value="room.rid" />
        </el-select>
      </el-form-item>
      <el-form-item label="Checkin" prop="time">
        <el-config-provider :locale="locale">
          <el-date-picker style="margin-top: 15px;" v-model="formModel.time" type="daterange" range-separator="至"
          start-placeholder="入住日期" end-placeholder="离开日期" :locale="locale"/>
        </el-config-provider>
      </el-form-item>

    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="resetForm(form)">重置</el-button>
        <el-button type="success" @click="AddOrder(form)">
          添加订单
        </el-button>
      </span>
    </template>
  </el-dialog>

  <el-table :data="tableData" style="width: 100%">
    <el-table-column prop="hname" label="酒店名" sortable width="150" />
    <el-table-column prop="checkInDate" label="入住日期" sortable width="150" />
    <el-table-column prop="checkOutDate" label="退房日期" sortable width="150" />
    <el-table-column prop="uid" label="入住人" sortable width="120" />
    <el-table-column prop="rname" label="房号" sortable width="120" />
    <el-table-column prop="price" label="价格" sortable width="120" />
    <el-table-column prop="payFlag" label="付款情况" sortable width="120" />
    <el-table-column fixed="right" label="操作" width="200">
      <template #default="scope">
        <el-button type="danger" size="small" @click="deleteOrder(scope.$index)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
</template>
<script lang="ts" setup>

import { componentSizeMap, type TableColumnCtx, ElMessageBox, FormInstance, FormRules } from 'element-plus'
import { reactive, ref, onMounted, resolveDirective } from 'vue';
import { getRequest, deleteRequest, postRequestWithFormData } from "../../api/axiosAPI";
import zhCn from 'element-plus/lib/locale/lang/zh-cn';



const dialogVisible = ref(false);

const form = ref<FormInstance>()

const hotelname = ref()

const formModel = ref({
  time: '',
  rid: '',
  hname: '',
})
const hoteldata = ref([
  {
    hid: '',
    name: '',
    address: '',
    phone: '',
    type: '',
    imgPath: '',
  }
])

const locale = ref(zhCn)

interface FormModel {
  hname: string
  rid: string
  time: string
}

// const switchToNum = (date) => {
//   switch (date) {
//     case 'Mon': date = '01'
//     case 'Tue': date = '02'
//     case 'Wed': date = '03'
//     case 'Apr': date = '04'
//     case 'Fri': date = '05'
//     case 'Jun': date = '06'
//     case 'Jul': date = '07'
//     case 'Aug': date = '08'
//     case 'Sep': date = '09'
//     case 'Oct': date = '10'
//     case 'Nov': date = '11'
//     case 'Dec': date = '12'
//   }
//   return date
// }

const switchToMonthNum = (month) => {
  switch (month) {
    case 'Jan': return '01'
    case 'Feb': return '02'
    case 'Mar': return '03'
    case 'Apr': return '04'
    case 'May': return '05' // 注意这里原来缺少了 'May'
    case 'Jun': return '06'
    case 'Jul': return '07'
    case 'Aug': return '08'
    case 'Sep': return '09'
    case 'Oct': return '10'
    case 'Nov': return '11'
    case 'Dec': return '12'
    default: return month // 或者抛出异常，因为输入不合法
  }
}

//通过form表单添加到table中
const AddOrder = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      let start_date = formModel.value.time[0].toString().split(' ')
      let end_date = formModel.value.time[1].toString().split(' ')
      let start_month = switchToMonthNum(start_date[1])
      let end_month = switchToMonthNum(end_date[1])
      let start_year = start_date[3]
      let end_year = end_date[3]
      let start_day = start_date[2]
      let end_day = end_date[2]
      let checkInDate = start_year + '-' + start_month + '-' + start_day
      let checkOutDate = end_year + '-' + end_month + '-' + end_day
      console.log("formModel.value.time:", formModel.value.time)
      console.log("开始日期:", start_date)
      console.log("结束日期:", end_date)
      console.log(checkInDate)
      console.log(checkOutDate)
      let order_data = {
        rid: formModel.value.rid,
        checkInDate: checkInDate,
        checkOutDate: checkOutDate
      }
      console.log(order_data.rid)
      postRequestWithFormData('http://localhost:8022/hotel/room/reserve', order_data) // 发起GET请求，假设接口地址为/api/data
        .then((response) => {
          if (response.status === 200) {
            console.log(response.data.data)
            console.log("请求成功")
            fetchData();
            dialogVisible.value = false
            formEl.resetFields()
          }
          else {
            console.log("NetWork Error");
          }
        })
        .catch((error) => {
          console.log(error);
        });
      // 表单验证通过，继续处理提交逻辑
      // tableData.value.push({ ...formModel.value})
    } else {
      // 表单验证不通过，提示错误信息
      window.alert('请填写表单')
      console.log('填写错误', fields)
    }
  })

}
//重置form表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const formRules = reactive<FormRules<FormModel>>({
  hname: [
    { required: true, message: 'Please enter the name', trigger: 'blur' },
  ],
  rid: [
    { required: true, message: 'Please enter the roomname', trigger: 'blur' },
  ],
  time: [
    { required: true, message: 'Please enter the time', trigger: 'blur' },
  ],
})

const deleteOrder = (index: number) => {
  if (window.confirm('请确认删除操作')) {
    console.log(index)
    console.log(tableData.value[index])
    var reid = tableData.value[index].reid
    deleteRequest(`http://localhost:8022/hotel/room/cancelReserve?reid=${reid}`, null) // 发起DELETE请求
      .then((response) => {
        if (response.status === 200) {
          console.log("删除成功")
          tableData.value.splice(index, 1)
        }
        else {
          console.log("NetWork Error");
        }
      })
      .catch((error) => {
        console.log(error);
      });
  }
  else {
    window.alert('操作已取消')
  }
}

onMounted(() => {
  fetchData();
  gethoteldata();
});

const gethoteldata = () => {
  getRequest('http://localhost:8022/hotel?type=nonstar')
    .then((response) => {
      if (response.status === 200) {
        // console.log('获取酒店信息')
        console.log(response.data.data)
        // hoteldata.value = response.data.data
        let tempData = response.data.data
        for (let i = 0; i < tempData.length; i++) {
          hoteldata.value[i] = {
            name: tempData[i].name,
            imgPath: tempData[i].imgPath,
            phone: tempData[i].phone,
            address: tempData[i].address,
            type: tempData[i].type,
            hid: tempData[i].hid
          }
        }
      }
      else {
        console.log('Network Error!')
      }
    })
    .catch((error) => {
      console.log(error)
    })
}

const fetchData = () => {
  getRequest('http://localhost:8022/hotel/room/getAllReserve', null) // 发起GET请求，假设接口地址为/api/data
    .then((response) => {
      if (response.status === 200) {
        // 将获取的数据存储到items属性中
        tableData.value.pop()
        for (let i = 0; i < response.data.data.length; i++) {
          if (response.data.data[i].hotelType == "民宿" || response.data.data[i].hotelType == "青年旅社") {
            tableData.value.push(response.data.data[i])
          }
        }
        for (let i = 0; i < response.data.data.length; i++) {
          if (tableData.value[i].payFlag == "0") {
            tableData.value[i].payFlag = "未付款"
          }
          else {
            tableData.value[i].payFlag = "已付款"
          }
          if (tableData.value[i].uid == "1") {
            tableData.value[i].uid = "Tom"
          }
        }
        console.log(response.data.data)
        console.log("请求成功")
      }
      else {
        console.log("NetWork Error");
      }
    })
    .catch((error) => {
      console.log(error);
    });
};

const selectHotelroom = (val) => {
  console.log(val)
  hotelname.value = val
  console.log(hotelname.value)
  getRequest(`http://localhost:8022/hotel/room/getByHid?hid=${hotelname.value}&available=true`, null)
    .then((response) => {
      if (response.status === 200) {
        // console.log('获取酒店信息')

        let tempData = response.data.data
        console.log(tempData)
        for (let i = 0; i < tempData.length; i++) {
          options.value[i] = {
            hid: tempData[i].hid,
            price: tempData[i].price,
            rid: tempData[i].rid,
            roomName: tempData[i].roomName,
            type: tempData[i].type,
            img: tempData[i].imgPath,
            id: i,
          }
        }
        console.log(options.value)
      }
      else {
        console.log('Network Error!')
      }
    })
    .catch((error) => {
      console.log(error)
    })
}

const tableData = ref([
  {
    checkInDate: '',
    checkOutDate: '',
    uid: '',
    rname: '',
    price: '',
    hname: '',
    payFlag: '',
    reid: '',
  }
])

const options = ref([{
  hid: '',
  price: 1,
  rid: '',
  roomName: '',
  type: '',
  img: '',
  id: 0,
}
])
</script>

  